<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/10/20
 * Time: 9:55 AM
 */

namespace app\common\controller;


use Qcloud\Cos\Client;
use think\Controller;
use Wechat\Cos;

class CosUpload extends Controller
{
    public function gettemkey($method,$pathname)
    {
        $config = array(
            'Url' => 'https://sts.api.qcloud.com/v2/index.php',
            'Domain' => 'sts.api.qcloud.com',
            'Proxy' => '',
            'SecretId' => 'AKID51oPnyzfBUaS6XwhOp0vZx5wXrwkHeiX', // 固定密钥
            'SecretKey' => 'iBOL2TeZEckcEaibGgrnUw98sOfiX7SY', // 固定密钥
            'Bucket' => 'payos-1251056009',
            'Region' => 'ap-shanghai',
            'AllowPrefix' =>'_ALLOW_DIR_/*' // 这里改成允许的路径前缀，这里可以根据自己网站的用户登录态判断允许上传的目录，例子：* 或者 a/* 或者 a.jpg
        );
        $Cos = new Cos($config);

        $tempKeys = $Cos->getTempKeys();
        if ($tempKeys && isset($tempKeys['credentials'])) {
            $data = $tempKeys;
            $data['Authorization'] = $Cos->getAuthorization($tempKeys, $method, $pathname);
            $data['XCosSecurityToken'] = $tempKeys['credentials']['sessionToken'];
        } else {
            $data = array('error' => $tempKeys);
        }

// 返回数据给前端
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: http://os.wunengkeji.com'); // 这里修改允许跨域访问的网站
        header('Access-Control-Allow-Headers: origin,accept,content-type');
        return $data;

    }

    public function uploads()
    {

        $cosClient = new Client(array(
            'region' => 'sh',
            'credentials' => array(
                'appId' => '1251056009',
                'secretId' => 'AKID51oPnyzfBUaS6XwhOp0vZx5wXrwkHeiX',
                'secretKey' => 'iBOL2TeZEckcEaibGgrnUw98sOfiX7SY',
            ),
        ));

        $bucket = 'payos';
        $key = 'jquery.min.js';
        $local_path = '/data2/html/payos/public/static/jquery.min.js';
        $result = $cosClient->putObject(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'Body' => 'Hello World!'
        ));
        return json(
            [
                "code" => 0,
                "msg" => '上传成功',
                "data" => [
                    "src" => str_replace("http://payos-1251056009.cos.ap-shanghai.myqcloud.com", "https://file.wunengkeji.com", $result['ObjectURL']),
                    "title" => ""
                ]
            ]
        );

    }

}